var util = require('./util.js');
var app = getApp();
var HOST;
/**
 * get请求
 * @param  {[type]} params [description]
 * @return {[type]}        [description]
 */
function _Get(params) {
  params = params || {};
  params.method = 'get';
  _request(params);
}

/**
 * post请求
 * @param  {[type]} params [description]
 * @return {[type]}        [description]
 */
function _Post(params) {
  params = params || {};
  params.method = 'post';
  _request(params);
}
/**
 * DELETE请求
 * @param  {[type]} params [description]
 * @return {[type]}        [description]
 */
function _Delete(params) {
  params = params || {};
  params.method = 'delete';
  _request(params);
}

/**
 * 异步请求基础方法
 * @param  {[type]} params [description]
 * @return {[type]}        [description]
 */
function _request(params) {
  var {
    method,
    url,
    data,
    success,
    fail,
    iHandleFail,
    isTips,
    unneedLoad
  } = params;
  // var userSid = app.getSid();

  var requestObj;
  var header = {};

  HOST = app.config.apiUrl;

  method = (method || 'get').toLowerCase();
  // url += '?alias=1';
  data = data || {};
  // data.userSid = userSid;
  if (method == 'post') {
    header['content-type'] = 'application/json';
  }

  if (!unneedLoad) {
    wx.showLoading({
      title: '请稍后...',
      mask: true
    })
  }

  


  requestObj = {
    url: HOST + url,
    header: header,
    method: method,
    success: function(res) {
      if (res.statusCode == 200) {
        var data = res.data;
        if (data.status == 1 || !data.status && data.status != 0) {
          typeof success == "function" && success(data, () => {
            !unneedLoad ? wx.hideLoading() : '';
          });
        } else {
          typeof fail == "function" && fail(data, isTips);
          if (!isTips) {
            util.tips(data.message);
          }
          if (iHandleFail) {
            return;
          }
        }
      } else if (res.statusCode == 500) {
        util.tips("服务器开小差了,正在紧急修复中");
      } else if (res.statusCode == 404) {
        util.tips("页面被劫持,正在努力寻找中");
      }
    },
    fail: function(res) {
      typeof fail == "function" && fail(res, isTips);
      util.tips(res.message);
    }
  };

  requestObj.data = data;

  wx.request(requestObj);


}

module.exports = {
  P: _Post,
  G: _Get,
  D: _Delete,
  request: _request
}